package com.century.sjt.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.activity.Pay.TransactionDataActivity;
import com.century.sjt.adapter.mPaynoTransactionAdapter;
import com.century.sjt.entity.noTransactionRecord;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商家用户
 * 待结算订单
 */
public class mTransaction_AccountFragment extends BaseFragment {
    private List<noTransactionRecord> mDataList;
    private ListView mListPtRecord;
    private mPaynoTransactionAdapter mAdapter;
    //    private Button loadMore;
    private Context mContext;
//    private String stype="3";

    private RequestQueue mQueue;
    private String pageSize="10";
    private int iCurrPage=1;
    private SwipeRefreshLayout mSwipeLayout;        //刷新组件
    private Handler mHandler;
    private Boolean isDataChangeOk=true;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.sjt_payno_transaction_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext=getActivity();
        mQueue = Volley.newRequestQueue(getActivity());

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        mAdapter.notifyDataSetChanged();
                        TipUtil.closeProgressDialog();
                        mSwipeLayout.setRefreshing(false);
                        break;
                    case 2:
                        isDataChangeOk=true;
                        mDataList.clear();
                        iCurrPage = 1;
                        getRecords();
                        break;
                    case 3:
                        if(isDataChangeOk) {
                            mSwipeLayout.setRefreshing(true);
                            iCurrPage++;
                            getRecords();
                        }
                        break;

                }
            }
        };
        initView();
        initEvents();

//        getStoreDetail(merchantId);


    }

    private void initEvents() {

        mAdapter=new mPaynoTransactionAdapter(mDataList,mContext,mQueue);
        mListPtRecord.setAdapter(mAdapter);

        mListPtRecord.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                // 当不滚动时
                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        Message msg = new Message();
                        msg.what = 3;
                        mHandler.sendMessage(msg);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        mListPtRecord.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                intent.setClass(mContext,TransactionDataActivity.class);
                intent.putExtra("payType", "2");
                String txNo=mDataList.get(i).getOrderNo();
                intent.putExtra("txNo",mDataList.get(i).getOrderNo());
                startActivity(intent);
            }
        });


        //更多记录
//        View bottomView=getLayoutInflater().inflate(R.layout.social_zone_listview_bottom, null);
//        loadMore=(Button)bottomView.findViewById(R.id.social_zone_listview_bottom_load);
//        loadMore.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                loadMore.setEnabled(false);
//                loadMore.setText("加载中");
//                getRecords();
//
//            }
//        });
//        mListPtRecord.addFooterView(bottomView);

        //刷新组件
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        });
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);

//        getRecords();
    }

    @Override
    public void onResume() {
//        getRecords();
        Message msg = new Message();
        msg.what = 2;
        mHandler.sendMessage(msg);
        super.onResume();
    }

    private void initView(){
        //刷新组件
        mSwipeLayout = (SwipeRefreshLayout)getView(). findViewById(R.id.activity_list_refesh);
        mQueue= Volley.newRequestQueue(mContext);
        mDataList=new ArrayList<>();
        mListPtRecord= (ListView)getView(). findViewById(R.id.list_pt_record);
    }

    //获取交易记录
    private void getRecords(){
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting),mContext);
        isDataChangeOk=false;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.MerNoSettleOrders, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    isDataChangeOk=true;
                    TipUtil.log("商家结算订单", response, 1);
//                    loadMore.setText("加载更多");
//                    loadMore.setEnabled(true);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");

                    if (code.equals("200")) {//成功
                        JSONArray data = res.getJSONArray("data");
                        if (data.length()!= Constant.PAGESIZE) {
                            isDataChangeOk = false;
                            if (iCurrPage == 1 && data.length() == 0) {
//                                TipUtil.showToast("暂无交易记录", mContext);
                            } else {
//                                TipUtil.showToast("无更多数据",PayTransactionActivity.this);
                            }
                        }
                        for(int i=0;i<data.length();i++){
                            JSONObject dataObject=data.getJSONObject(i);
                            noTransactionRecord transactionRecord=new noTransactionRecord();
//
//                            : {"orderStatus":"已支付"
//                                    ,"orderTime":"2016-04-06 20:12:44",
//                                    "orderAmount":"70.40",
//                                    "orderUser":"帅得不要不要",
//                                    "userMobile":"18033940592",
//                                    "orderMerchant":"豪客来",
//                                    "orderNo":"20160406100000000022",
//                                    "orderPayType":"卡支付",
//                                    "payCardNo":"2524",
//                                    "bankCode":"5"}
                            transactionRecord.setOrderStatus(dataObject.getString("orderStatus"));
                            transactionRecord.setOrderTime(dataObject.getString("orderTime"));
                            transactionRecord.setOrderAmount(dataObject.getString("orderAmount"));
                            transactionRecord.setOrderUser(dataObject.getString("orderUser"));
                            transactionRecord.setUserMobile(dataObject.getString("userMobile"));
                            transactionRecord.setOrderMerchant(dataObject.getString("orderMerchant"));
                            transactionRecord.setOrderNo(dataObject.getString("orderNo"));
                            transactionRecord.setOrderPayType(dataObject.getString("orderPayType"));
                            transactionRecord.setPayCardNo(dataObject.getString("payCardNo"));
                            transactionRecord.setBankCode(dataObject.getString("bankCode"));
                            mDataList.add(transactionRecord);
                        }

                    } else {//失败
                        TipUtil.showToast(message, mContext, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), mContext, 1);
                }
                TipUtil.closeProgressDialog();
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
                isDataChangeOk=true;
                iCurrPage--;
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("paging.pageSize", Constant.PAGESIZE+"");
                map.put("paging.currentPage",String.valueOf(iCurrPage));
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }




    @Override
    public void onDestroy() {
        mQueue.cancelAll(this);
        super.onDestroy();
    }
}
